package com.baseandroid.jpush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.androidbase.utils.AndroidUtils;
import com.androidbase.webview.WebViewTbsActivity;
import com.baseandroid.config.Global;
import com.baseandroid.event.PaysuccessEvent;
import com.baseandroid.push.PushDoneService;
import com.baseandroid.utils.NotificationUtils;
import com.qianbao.qianbaobusiness.json.DataListBean;
import com.qianbao.qianbaobusiness.ui.cashier.CashierDetailActivity;
import com.qianbao.qianbaobusiness.ui.home.HomeActivity;
import com.qianbao.qianbaobusiness.ui.push.PushMsgDetailActivity;
import com.qianbao.qianbaobusiness.ui.webview.SimpleWebViewActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.Random;

import cn.jpush.android.api.JPushInterface;

public class MyJPushReceiver extends BroadcastReceiver {

    private static final String TAG = BroadcastReceiver.class.getSimpleName();

    private static final String CT_TEXT = "01";// 文本
    private static final String CT_URL = "02";// 地址URL
    private static final String CT_APP = "03";// APP界面
    private static final int FROM_JPUSH = 1;// 从通知栏打开页面
    private static final int FROM_APP = 2;// 从应用内部打开页面

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "Registration Id : " + regId);
            // send the Registration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "Received Message: " + printBundle(context, bundle));

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "Received Notification: " + printBundle(context, bundle));

            int notificationId = new Random().nextInt(1000) % (1000 - 25 + 1) + 25;
            NotificationUtils notificationUtils = new NotificationUtils(context);
            try {
                JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                Log.d(TAG, "Extra Json: " + json);
                String msg_title = bundle.getString(JPushInterface.EXTRA_ALERT); //极光消息体内容
                String title = json.getString("title"); //通知栏显示内容
                String contenttype = json.getString("contenttype");
                String messageNo = json.getString("messageno");
                String content = json.getString("content");
                if (TextUtils.equals(contenttype, CT_TEXT)) {
                    int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP;
                    Bundle b = new Bundle();
                    b.putString("contenttype", contenttype);
                    b.putString("messageNo", messageNo);// 消息编号
                    b.putString("title", "消息"); // 标题栏文本
                    b.putString("msg_title", title);// 消息标题
                    b.putString("content", content);// 消息内容
                    if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                            .getPackageName())) {
                        Intent i = context.getPackageManager()
                                .getLaunchIntentForPackage(context.getPackageName());
                        i.setFlags(flags);
                        b.putInt("open_flag", FROM_JPUSH);
                        i.putExtras(b);
                        notificationUtils.sendNotification(title, notificationId, i);
                    } else {
                        b.putInt("open_flag", FROM_APP);
                        Intent intentJpushMsg = new Intent(context, PushMsgDetailActivity.class);
                        intentJpushMsg.putExtras(b);
                        intentJpushMsg.setFlags(flags);
                        notificationUtils.sendNotification(title, notificationId, intentJpushMsg);
                    }

                } else if (TextUtils.equals(contenttype, CT_URL)) {
                    int flags = Intent.FLAG_ACTIVITY_NEW_TASK;
                    Bundle b = new Bundle();
                    b.putString("contenttype", contenttype);
                    b.putString("title", "消息");
                    b.putString("url", content);
                    if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                            .getPackageName())) {
                        Intent i = context.getPackageManager()
                                .getLaunchIntentForPackage(context.getPackageName());
                        i.setFlags(flags);
                        b.putInt("open_flag", FROM_JPUSH);
                        i.putExtras(b);
                        notificationUtils.sendNotification(title, notificationId, i);
                    } else {
                        b.putInt("open_flag", FROM_APP);
                        Intent intentOtherWeb = new Intent(context, SimpleWebViewActivity.class);
                        intentOtherWeb.setFlags(flags);
                        intentOtherWeb.putExtras(b);
                        intentOtherWeb.putExtra(WebViewTbsActivity.WEBVIEW_TITLE, b.getString("title"));
                        intentOtherWeb.putExtra(WebViewTbsActivity.WEBVIEW_URL, b.getString("url"));
                        notificationUtils.sendNotification(title, notificationId, intentOtherWeb);
                    }
                } else if (TextUtils.equals(contenttype, CT_APP)) {// 跳转app内部页面
                    if (!TextUtils.isEmpty(content)) {
                        if (content.contains("?")) {
                            String[] to = content.split("\\?");
                            String toWhere = to[0]; // merchant_detail
                            String param = to[1];   // merchantNo=M20160101100009
                            if (TextUtils.equals(toWhere, "order_detail")) {// 打开“订单详情”
                                // 举例：order_detail?orderNo=ORD2015080410000000000424
                                if (!TextUtils.isEmpty(param) && param.contains("orderNo=")) {
                                    String orderno = param.split("orderNo=")[1];
                                    int flags = Intent.FLAG_ACTIVITY_NEW_TASK;
                                    Bundle b = new Bundle();
                                    b.putString("contenttype", contenttype);
                                    b.putString("toWhere", "order_detail");
                                    b.putString("orderno", orderno);
                                    if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                                            .getPackageName())) {
                                        Intent i = context.getPackageManager()
                                                .getLaunchIntentForPackage(context.getPackageName());
                                        i.setFlags(flags);
                                        b.putInt("open_flag", FROM_JPUSH);
                                        i.putExtras(b);
                                        notificationUtils.sendNotification(title, notificationId, i);
                                    }
                                }
                            }
                        } else {
                            if (content.contains("order_list")) {// 打开“交易列表”
                                int flags = Intent.FLAG_ACTIVITY_NEW_TASK;
                                Bundle b = new Bundle();
                                b.putString("contenttype", contenttype);
                                b.putString("toWhere", "order_list");
                                if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                                        .getPackageName())) {
                                    Intent i = context.getPackageManager()
                                            .getLaunchIntentForPackage(context.getPackageName());
                                    i.setFlags(flags);
                                    b.putInt("open_flag", FROM_JPUSH);
                                    i.putExtras(b);
                                    notificationUtils.sendNotification(title, notificationId, i);
                                }
                            } else if (content.contains("index")) {// 打开“app首页”
                                int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP;
                                Bundle b = new Bundle();
                                b.putString("contenttype", contenttype);
                                b.putString("toWhere", "index");
                                if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                                        .getPackageName())) {
                                    Intent i = context.getPackageManager()
                                            .getLaunchIntentForPackage(context.getPackageName());
                                    i.setFlags(flags);
                                    b.putInt("open_flag", FROM_JPUSH);
                                    i.putExtras(b);
                                    notificationUtils.sendNotification(title, notificationId, i);
                                } else {
                                    Intent intentHome = new Intent(context, HomeActivity.class);
                                    if (b != null) {
                                        intentHome.putExtras(b);
                                    }

                                    intentHome.setFlags(flags);
                                    notificationUtils.sendNotification(title, notificationId, intentHome);
                                }
                            } else if (content.contains("getOrderInfo")) {
                                int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP;
                                Bundle b = new Bundle();
                                String orderno = json.getString("orderno");
                                String merchantno = json.getString("merchantno");
                                b.putString("merchantNo", merchantno);
                                b.putString("orderNo", orderno);
                                if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                                        .getPackageName())) {
                                    Intent i = context.getPackageManager()
                                            .getLaunchIntentForPackage(context.getPackageName());
                                    i.setFlags(flags);
                                    b.putInt("open_flag", FROM_JPUSH);
                                    i.putExtras(b);
                                    notificationUtils.sendNotification(title, notificationId, i);
                                } else {
                                    if (Global.getPushBillState()) {
                                        Intent intentTransaction = new Intent(context, CashierDetailActivity.class);
                                        if (b != null) {
                                            intentTransaction.putExtras(b);
                                        }
                                        /*--传递DataListBean数据--*/
                                        DataListBean dataListBean = new DataListBean();
                                        dataListBean.setMerchantNo(merchantno);
                                        dataListBean.setOrderNo(orderno);
                                        intentTransaction.putExtra("bean", dataListBean);
                                        intentTransaction.setFlags(flags);
                                        notificationUtils.sendNotification(title, notificationId, intentTransaction);
                                    }
                                }
                            }
                        }
                        // 支付成功通知首页更新
                        EventBus.getDefault().post(new PaysuccessEvent());
                    }
                }

                /*--后台服务进行统计、语音播报--*/
                String contentbt = json.getString("content");
                String paytime = json.optString("paytime");
                String titlebt = json.getString("title");
                String isvoice = json.getString("isvoice");
                String msgpushts = json.optString("msgpushts");
                String msgpushid = json.getString("msgpushid");
                String msgpushch = json.getString("msgpushch");
                Intent i = new Intent(context, PushDoneService.class);
                i.putExtra("isvoice", isvoice);
                i.putExtra("msg", titlebt);
                i.putExtra("msgpushts", msgpushts);
                i.putExtra("msgpushid", msgpushid);
                i.putExtra("msgpushch", msgpushch);
                i.putExtra("orderts", paytime);
                i.putExtra("localmills", System.currentTimeMillis() + "");
                context.startService(i);
            } catch (JSONException e) {
                Log.e(TAG, "Get message extra JSON error! " + e.toString());
            }

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "Action Notification Opened" + printBundle(context, bundle));

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "Action Richpush Callback: " + printBundle(context, bundle));

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "connected state change to " + connected);

        } else {
            Log.d(TAG, "Unhandled intent - " + intent.getAction());
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Context context, Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    continue;
                }
                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (key.equals(JPushInterface.EXTRA_ALERT)) {
                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it1 = json.keys();
                    while (it1.hasNext()) {
                        String myKey = it1.next().toString();
                        sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json.optString(myKey) + "]");
                    }
                    String payType = json.getString("type");
                    if (!TextUtils.isEmpty(payType) && "paySuccess".equals(payType)) {
                        //						player(context);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

}
